package com.gitee.shigen.config;

import com.gitee.shigen.service.MainService;
import java.util.Date;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

/**
 * @author shigenfu
 * @date 2023/12/27 11:05
 */
@Configuration
@EnableScheduling
@Slf4j
public class SchedulingConfigure implements SchedulingConfigurer {

    @Resource
    private SyncConfig syncConfig;
    @Resource
    private MainService mainService;

    private String getCron() {
        String cron = syncConfig.getCron();
        log.info("cron:---{}", cron);
        return cron;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                // 定时执行的任务
                log.info("------------start task-------------------");
                mainService.sync();
                log.info("--------------end task-------------------");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String cron = getCron();
                // 任务触发，可修改任务周期
                CronTrigger cronTrigger = new CronTrigger(cron);
                return cronTrigger.nextExecutionTime(triggerContext);
            }
        });
    }
}
